import { Button, message, Modal,Tooltip } from 'antd';
import React, { useState, useRef, useEffect ,useContext} from 'react';
import ProTable from '@ant-design/pro-table';
import AddForm from './components/AddForm';
import { addTag, updateTaskTag, removeTag, queryTaskTagList } from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { UserContext } from '@/layouts/UserProvider';

const TableList = (props) => {
  useEffect(() => {
    queryTaskTagList({ id: 1 });
  }, []);
  const userCtx = useContext(UserContext);
  const permits=userCtx.userPermits;
  const userInfo = userCtx.userInfo;
  const handleDelTag = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        removeTag({ id: record.id }).then((data) => {

          if (actionRef.current) {
            actionRef.current.reload();
          }
        });
      },
    });
  };
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const [type, setType] = useState('');
  const actionRef = useRef();
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
      await addTag({
        name: fields.name,
        id: '',
      }).then((data)=>{
        hide();
        if(data.code=='200'){
          message.success('添加成功');
          handleDetailModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }else{
          message.error('添加失败请重试！');
        }
      })
    } catch (error) {
      hide();
      console.log('taskTag handleAdd catch: ' + error)
      message.error('添加失败请重试！');
    }
  };
  const handleUpdate = async (fields) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateTaskTag({
        name: fields.name,
        id: fields.id,
      });
      hide();
      if (res.code == '200') {
        message.success('修改成功');
        handleDetailModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error('修改失败请重试！');
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
    }
  };
  const handleFun = async (params) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateTaskTag(params);
      hide();
      if (res.code == '200') {
        message.success('修改成功');
      } else {
        message.error('修改失败请重试！');
        return false;
      }
      return true;
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      return false;
    }
  };
  const handleUpdateStatus = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要修改状态？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleFun({ 
          id: record.id,
          is_active: record.is_active == 1 ? 2 : 1,}).then((data)=>{
            if (actionRef.current) {
              actionRef.current.reload();
            }
          })
        console.log(record.id);
       },
    });
  };

  const columns = [
    {
      title: '任务标签',
      dataIndex: 'name',
      with: '100px',
      ellipsis: {
        showTitle: false,
      },
      render: address => (
        <Tooltip placement="topLeft" title={address}>
          {address}
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '全局',
          status: 'Default',
        },
        1: {
          text: '启用',
          status: 'Processing',
        },
        2: {
          text: '禁用',
          status: 'Success',
        },
      },
      render: (is_active) => <>{is_active}</>,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let res=[]
        if(permits.includes('updateTskTag')&&record.is_system_tag!==1&& (userInfo.user_id == record.creator_id || ['1', '4'].includes(String(userInfo?.type)))){
          res= [
            <Button
              size="small"
              key="edit"
              onClick={() => {
                handleDetailModalVisible(record);
                setType(1);
              }}
            >
              编辑
            </Button>,
            <Button
              size="small"
              key="search"
              onClick={() => {
                handleUpdateStatus(record);
                setType(2);
              }}
            >
              {record.is_active == 1 ? '禁用' : '启用'}
            </Button>,
          ];
        }
          if(permits.includes('deleteTskTag')&&record.is_system_tag!==1&& (userInfo.user_id == record.creator_id || ['1', '4'].includes(String(userInfo?.type)))){
            res.push(<Button size="small" key="detail" onClick={() => handleDelTag(record)}>
            删除
          </Button>)
          }

        return res
      }
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={{
          collapsed: false,
          defaultCollapsed: false,
          collapseRender: () => '',
          labelWidth: 120,
          searchText: '搜索',
        }}
        request={async (params, sorter, filter) =>{
          try{
            console.log('*****params*******');
            console.log(params);
            params.is_active = parseInt(params.is_active);
            params.is_total=true;
            params.limit=params.pageSize;
            params.offset = (params.current - 1) * params.pageSize;
            let res = await queryTaskTagList({ ...params, sorter, filter });
            if (res.data == null && res.total != 0) {
              params.current = params.current - 1;
              params.offset = (params.current - 1) * params.pageSize;
              res = await queryTaskTagList({ ...params, sorter, filter });
            }
            return {data: JSON.stringify(res.data) != '{}'?res.data:[], success: true, total: res.total || 0}
          }catch(error){
            return { data: [], success: false, total: 0}
          }
         }
        }
        columns={columns}
        toolBarRender={() => {
          let res = [];
          if (permits.includes('addTskTag')) {
            res.push(<Button
              type="primary"
              key="primary"
              onClick={() => {
                handleDetailModalVisible(true);
                setType(0);
              }}
            >
              添加任务标签
            </Button>)
          }
          return res ;
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize: 10,
        }}
      />
      <AddForm
        onSubmit={async (value) => {
          console.log('&&&&&&&&&&&&&&');
          console.log(type);
          //添加
          if (type == 0) {
            await handleAdd(value);
          } else {
            await handleUpdate(value);
          }
        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        type={type}
        updateModalVisible={updateModalVisible}
      />
    </>
  );
};

export default connect(({login})=>{
  return {
     userType:login.type?login.type:1
  }
})(TableList);
